package com.google.sydym6.logic.database;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class RadioDBHelper extends SQLiteOpenHelper {
	private static String DB_PATH;
	private int tableVersion;
	private static final String TABLE_VERSION_PREF = "table_version_pref";
	private static final String VERSION = "version";
	private static final int mode = Activity.MODE_PRIVATE;
	
	private SQLiteDatabase database;
	private Context context;
	private SharedPreferences sharedPreferences;
	
	public RadioDBHelper(Context context) {
		super(context, DBConstants.DATABASE, null, 1);
		this.context = context;
		
		sharedPreferences = context.getSharedPreferences(TABLE_VERSION_PREF, mode);
		Log.v("database", "Shared preference: " + sharedPreferences);
		tableVersion = sharedPreferences.getInt(VERSION, -1);
		
		String packageName = context.getPackageName();
		DB_PATH = String.format("//data//data//%s//databases//", packageName);
		openDataBase();
	}
	
	public void createDataBase() {
		boolean dbExist = checkDataBase();
		if (!dbExist) {
			try {
				copyDataBase();
			} catch (IOException e) {
				Log.w("database", e.getMessage());
				Log.e("database", "Copying error");
				throw new Error("Error copying database!");
			}
		} else {
			Log.i(this.getClass().toString(), "Database already exists");
		}
	}
	
	private boolean checkDataBase() {
		SQLiteDatabase checkDb = null;
		int version = -1;
		try {
			String path = DB_PATH + DBConstants.DATABASE;
			checkDb = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
			 version = checkDb.getVersion();
			 Log.v("database", "Db version: " + version);
		} catch (SQLiteException e) {
			Log.e("database", "Error while checking db");
		}
		
		if (checkDb != null) {
			checkDb.close();
		}
		
		boolean equalsVersion = true;
		
		if (tableVersion != version) {
			Log.v("database", "Versions is not equals");
			equalsVersion = false;
			tableVersion = version;
			SharedPreferences.Editor editor = sharedPreferences.edit();
			editor.putInt(VERSION, version);
			editor.commit();
		}
		
		return ((checkDb != null)&&(equalsVersion));
	}
	
	private void copyDataBase() throws IOException {
		
		InputStream externalDbStream = context.getAssets().open(DBConstants.DATABASE);
		Log.v("database", "Creates Inputstream");

		String outFileName = DB_PATH + DBConstants.DATABASE;
		File localDbFile = new File(DB_PATH);
		Log.v("database", "creates file");
		localDbFile.mkdirs();
		Log.v("database", "creates dirs");

		OutputStream localDbStream = new FileOutputStream(outFileName);

		Log.v("database", "Creates streams");
		byte[] buffer = new byte[1024];
		int bytesRead;
		while ((bytesRead = externalDbStream.read(buffer)) > 0) {
			localDbStream.write(buffer, 0, bytesRead);
		}
		
		localDbStream.close();
		externalDbStream.close();
	}

	public SQLiteDatabase openDataBase() throws SQLException {
		String path = DB_PATH + DBConstants.DATABASE;
		if (database == null) {
			createDataBase();
			
			database = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READWRITE);

			//database.execSQL(CREATE_MUSIC_HISTORY_TABLE);
			//Log.v("database", "Music history table created");
			Cursor cursor = database.rawQuery("SELECT * FROM history", null);
			Log.v("database", "History table rows: " + cursor.getCount());
		}
		return database;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
	}
	
	@Override
	public synchronized void close() {
	    if(database != null)
	    	database.close();

	    super.close();
	}

}
